package com.koron.css2.baseConfig.impl;

import com.google.common.collect.Lists;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.BaseAccessoryMetadataBean;
import com.koron.css2.baseConfig.bean.BaseReceiptAccessoryBean;
import com.koron.css2.baseConfig.mapper.BaseAccessoryMetadataMapper;
import com.koron.css2.baseConfig.mapper.BaseReceiptAccessoryMapper;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 附件删除
 * @author bin
 *
 */
public class AccessoryDelete implements ServerInterface{
	
	private static Logger log = LogManager.getLogger(AccessoryDelete.class);
	
	private static final Map<String, String> FTOKEN = new ConcurrentHashMap<String, String>();

	@Override
	@Transactional
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			String ids = JsonUtils.objectToPojo(req.getData(), String.class);
//			Map<String, Object> reqDataMap = JsonUtils.objectToPojo(req.getData(), Map.class);
//			String ids = String.valueOf(reqDataMap.get("ids"));
			BaseReceiptAccessoryMapper mapper = factory.getMapper(BaseReceiptAccessoryMapper.class);
			BaseAccessoryMetadataMapper metadataMapper = factory.getMapper(BaseAccessoryMetadataMapper.class);
			List<String> list = Lists.newArrayList(ids.split(",", -1));
			List<String> path = new ArrayList<>();
			for(String l : list) {
				BaseReceiptAccessoryBean receiptAccessory = mapper.selectById(l);
				if(StringUtils.isNotBlank(receiptAccessory.getCreateAccount())
						&& !userInfo.getUserInfo().getAcount().equals(receiptAccessory.getCreateAccount()))
					return MessageBean.create(Constant.MESSAGE_DBFAIL, "无权限删除该附件", void.class);
				BaseAccessoryMetadataBean metadata = metadataMapper.selectById(receiptAccessory.getMetadataId());
				if(metadata!=null &&  StringUtils.isNoneBlank(metadata.getAccessoryPath()))
					path.add(metadata.getAccessoryPath());
				int iCount = metadataMapper.deleteById(receiptAccessory.getMetadataId());
				iCount = mapper.deleteById(l);
				if(iCount > 0) {
					log.info("已删除附件：{}", receiptAccessory.getAccessoryName());
				}
			}
			String ftoken = getFToken();
			for(String l:path) {
				delete(ftoken,l);
			}
			return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "文件删除成功", void.class);
		}catch (Exception e) {
			log.error("文件删除失败",e);
			return MessageBean.create(Constant.MESSAGE_DBFAIL, "文件删除失败", void.class);
		}
	}
	

	private void delete(String ftoken,String accessoryPath) {
		try {
			Map<String, String> data = new HashMap<String, String>();
			data.put("ftoken", ftoken);
			data.put("path",accessoryPath);
			
			String result = HttpUtils.sendPostForm(ApplicationConfig.getAccessoryUploadUrl() + "fileDelete", data);
			log.info("文件删除结果返回：{}", result);
			MessageBean<?> message = JsonUtils.jsonToPojo(result, MessageBean.class);
			if(message.getCode() != Constant.MESSAGE_INT_SUCCESS) {
				log.error(accessoryPath+"文件删除失败：" + message.getDescription());
			} 
		}catch(Exception e) {
			log.error("文件删除失败:"+accessoryPath);
		}
	}
	
	@SuppressWarnings("unchecked")
	private String getFToken() throws Exception {
		if(FTOKEN.get("time") != null && (System.currentTimeMillis() - Long.parseLong(FTOKEN.get("time"))) < (30 * 60 * 1000)) {
			return FTOKEN.get("ftoken");
		}
		Map<String, String> data = new HashMap<String, String>();
		data.put("appid", ApplicationConfig.getAccessoryAppId());
		data.put("secret", ApplicationConfig.getAccessorySecret());
		String result = HttpUtils.sendPostJson(ApplicationConfig.getAccessoryUploadUrl() + "fileAuthorize", JsonUtils.objectToJson(data));
		log.info("文件上传获取token结果返回：{}", result);
		MessageBean<?> message = JsonUtils.jsonToPojo(result, MessageBean.class);
		if(message.getCode() != Constant.MESSAGE_INT_SUCCESS) {
			throw new RuntimeException("获取 FTOKEN失败:" + message.getDescription());
		}
		Map<String, String> map = JsonUtils.objectToPojo(message.getData(), Map.class);
		FTOKEN.put("time", System.currentTimeMillis() + "");
		FTOKEN.put("ftoken", map.get("ftoken"));
		return map.get("ftoken");
	}


}
